const axios = require('axios');
const { City, Weather, User, UserCity, WeatherCache } = require('../models');
const weatherService = require('../services/weatherService');
const { Op } = require('sequelize');

// 获取当前天气
const getCurrentWeather = async (req, res) => {
  try {
    const userId = req.user.user_id;
    let user = await User.findByPk(userId, {
      include: [{
        model: City,
        through: { model: UserCity, where: { is_default: true } }
      }]
    });

    let targetCity = null;

    if (user && user.Cities && user.Cities.length > 0) {
      targetCity = user.Cities[0];
      console.log(`[getCurrentWeather] 找到默认城市: ${targetCity.name}`);
    }

    if (!targetCity) {
      console.log('[getCurrentWeather] 未找到默认城市。');
      return res.status(404).json({ error: '未能获取到默认城市信息，请确保已设置默认城市或允许浏览器定位' });
    }

    const city = targetCity;
    console.log('[getCurrentWeather] 使用的默认城市:', city);

    // 调用高德天气API获取实时天气
    console.log(`[getCurrentWeather] 准备请求高德实时天气，城市编码: ${city.city_code}`);
    const weatherResponse = await axios.get('https://restapi.amap.com/v3/weather/weatherInfo', {
      params: {
        key: process.env.AMAP_KEY,
        city: city.city_code,
        extensions: 'base'
      }
    });

    if (weatherResponse.data.status !== '1') {
      console.error('[getCurrentWeather] 高德实时天气API返回错误:', weatherResponse.data);
      return res.status(500).json({ error: '获取天气信息失败' });
    }

    const weatherData = weatherResponse.data.lives[0];
    console.log('[getCurrentWeather] 从高德获取到的实时天气数据:', weatherData);

    // 将实时天气数据保存到历史缓存表
    try {
      const reportDate = new Date(weatherData.reporttime);
      const formattedReportDate = reportDate.toISOString().slice(0, 10); // 获取 YYYY-MM-DD 格式的日期

      // 检查当天该城市是否已有记录
      const existingRecord = await WeatherCache.findOne({
        where: {
          city_id: city.city_code,
          date: { [Op.gte]: new Date(formattedReportDate + 'T00:00:00.000Z'), [Op.lt]: new Date(formattedReportDate + 'T23:59:59.999Z') },
        },
      });

      if (existingRecord) {
        console.log(`[getCurrentWeather] 实时天气数据已存在，跳过缓存: ${city.city_code} - ${formattedReportDate}`);
      } else {
        const cachedWeather = await WeatherCache.create({
          city_id: city.city_code, // Changed to city.city_code to store adcode
          date: reportDate, // 确保日期格式正确
          temperature: parseFloat(weatherData.temperature),
          wind_speed: parseFloat(weatherData.windpower), // 高德实时天气API中，windpower代表风力，这里映射到wind_speed
          air_quality: null, // 高德实时天气API通常不直接提供空气质量
          precipitation: null, // 高德实时天气API通常不直接提供降水量
          weather_condition: weatherData.weather, // 新增：保存天气描述
        });
        console.log('[getCurrentWeather] 实时天气数据已成功缓存到 WeatherCache。', cachedWeather.toJSON());
      }

      // 清理超过15天的数据
      const fifteenDaysAgo = new Date();
      fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 15);
      const deletedCount = await WeatherCache.destroy({
        where: {
          date: { [Op.lt]: fifteenDaysAgo },
          city_id: city.city_code, // 只清理当前城市超过15天的数据
        }
      });
      console.log(`[getCurrentWeather] 已清理 WeatherCache 中 ${deletedCount} 条超过15天的数据。`);

    } catch (cacheError) {
      console.error('缓存实时天气数据失败或清理过期数据失败:', cacheError.message, cacheError.stack);
      // 可以选择是否阻止响应，通常缓存失败不应该影响主请求
    }

    res.json({
      province: weatherData.province,
      city_name: weatherData.city, // 使用高德API返回的城市名称
      adcode: weatherData.adcode,
      temperature: weatherData.temperature,
      description: weatherData.weather,
      winddirection: weatherData.winddirection,
      windpower: weatherData.windpower,
      humidity: weatherData.humidity,
      date: weatherData.reporttime
    });
  } catch (error) {
    console.error('获取天气信息失败:', error.message, error.stack);
    res.status(500).json({ error: '获取天气信息失败', details: error.message });
  }
};

// 根据城市ID获取天气
const getWeatherByCityId = async (req, res) => {
  try {
    const { cityId } = req.params;
    const city = await City.findByPk(cityId);
    
    if (!city) {
      return res.status(404).json({ error: '城市不存在' });
    }

    // 获取城市经纬度
    const geocodeResponse = await axios.get('https://restapi.amap.com/v3/geocode/geo', {
      params: {
        key: process.env.AMAP_KEY,
        address: city.name,
        city: city.name
      }
    });
    console.log(`[getWeatherByCityId] 高德地理编码API响应: ${JSON.stringify(geocodeResponse.data)}`);

    if (geocodeResponse.data.status !== '1' || !geocodeResponse.data.geocodes.length) {
      return res.status(404).json({ error: '无法获取城市地理信息' });
    }

    const location = geocodeResponse.data.geocodes[0].location;
    const [longitude, latitude] = location.split(',');

    // 调用高德天气API
    const weatherResponse = await axios.get('https://restapi.amap.com/v3/weather/weatherInfo', {
      params: {
        key: process.env.AMAP_KEY,
        city: city.city_code,
        extensions: 'base'
      }
    });
    console.log(`[getWeatherByCityId] 高德天气API响应: ${JSON.stringify(weatherResponse.data)}`);

    if (weatherResponse.data.status !== '1') {
      return res.status(500).json({ error: '获取天气信息失败' });
    }

    const weatherData = weatherResponse.data.lives[0];
    console.log('[getWeatherByCityId] Sending current weather data to frontend:', weatherData);

    // 将实时天气数据保存到历史缓存表
    try {
      const reportDate = new Date(weatherData.reporttime);
      const formattedReportDate = reportDate.toISOString().slice(0, 10); // 获取 YYYY-MM-DD 格式的日期

      // 检查当天该城市是否已有记录
      const existingRecord = await WeatherCache.findOne({
        where: {
          city_id: city.city_code,
          date: { [Op.gte]: new Date(formattedReportDate + 'T00:00:00.000Z'), [Op.lt]: new Date(formattedReportDate + 'T23:59:59.999Z') },
        },
      });

      if (existingRecord) {
        console.log(`[getWeatherByCityId] 实时天气数据已存在，跳过缓存: ${city.city_code} - ${formattedReportDate}`);
      } else {
        const cachedWeather = await WeatherCache.create({
          city_id: city.city_code, // Store adcode as city_id
          date: reportDate, // Ensure date format is correct
          temperature: parseFloat(weatherData.temperature),
          wind_speed: parseFloat(weatherData.windpower), // In Gaode real-time weather API, windpower represents wind force, mapped to wind_speed here
          air_quality: null, // Gaode real-time weather API usually does not directly provide air quality
          precipitation: null, // Gaode real-time weather API usually does not directly provide precipitation
          weather_condition: weatherData.weather, // New: save weather description
        });
        console.log('[getWeatherByCityId] 实时天气数据已成功缓存到 WeatherCache。', cachedWeather.toJSON());
      }

      // 清理超过15天的数据
      const fifteenDaysAgo = new Date();
      fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 15);
      const deletedCount = await WeatherCache.destroy({
        where: {
          date: { [Op.lt]: fifteenDaysAgo },
          city_id: city.city_code, // Only clear data older than 15 days for the current city
        }
      });
      console.log(`[getWeatherByCityId] 已清理 WeatherCache 中 ${deletedCount} 条超过15天的数据。`);

    } catch (cacheError) {
      console.error('getWeatherByCityId 缓存实时天气数据失败或清理过期数据失败:', cacheError.message, cacheError.stack);
      // Choose whether to block the response, usually cache failure should not affect the main request
    }

    res.json({
      province: weatherData.province,
      city_name: weatherData.city, // Use city name returned by Gaode API
      adcode: weatherData.adcode,
      temperature: weatherData.temperature,
      description: weatherData.weather,
      winddirection: weatherData.winddirection,
      windpower: weatherData.windpower,
      date: weatherData.reporttime
    });
  } catch (error) {
    console.error('获取天气信息失败:', error);
    res.status(500).json({ error: '获取天气信息失败', details: error.message });
  }
};

const getForecastWeather = async (req, res) => {
  try {
    const { cityId } = req.params;
    const city = await City.findByPk(cityId);
    
    if (!city) {
      return res.status(404).json({ error: '城市不存在' });
    }

    // 获取城市经纬度
    const geocodeResponse = await axios.get('https://restapi.amap.com/v3/geocode/geo', {
      params: {
        key: process.env.AMAP_KEY,
        address: city.name,
        city: city.name
      }
    });
    console.log(`[getForecastWeather] 高德地理编码API响应: ${JSON.stringify(geocodeResponse.data)}`);

    if (geocodeResponse.data.status !== '1' || !geocodeResponse.data.geocodes.length) {
      return res.status(404).json({ error: '无法获取城市地理信息' });
    }

    const location = geocodeResponse.data.geocodes[0].location;
    const [longitude, latitude] = location.split(',');

    // 调用高德天气API获取预报
    const weatherResponse = await weatherService.fetchForecastWeather(city.city_code);
    console.log(`[getForecastWeather] 高德天气预报API响应: ${JSON.stringify(weatherResponse)}`);

    if (weatherResponse.status !== '1' || !weatherResponse.forecasts || weatherResponse.forecasts.length === 0) {
      console.error(`[getForecastWeather] 高德天气预报API返回非成功状态或无预报数据: ${JSON.stringify(weatherResponse)}`);
      return res.status(500).json({ error: '获取天气预报失败', details: weatherResponse.info || '高德API返回异常' });
    }

    const forecasts = weatherResponse.forecasts[0].casts.map(cast => ({
      date: cast.date,
      week: cast.week,
      day_weather: cast.dayweather,
      night_weather: cast.nightweather,
      day_temp: cast.daytemp,
      night_temp: cast.nighttemp,
      day_wind: cast.daywind,
      night_wind: cast.nightwind,
      day_power: cast.daypower,
      night_power: cast.nightpower
    }));

    console.log('[getForecastWeather] Sending forecast weather data to frontend:', { city_name: city.name, forecasts });
    res.json({
      city_name: city.name,
      forecasts
    });
  } catch (error) {
    console.error('获取天气预报失败:', error);
    res.status(500).json({ error: '获取天气预报失败', details: error.message });
  }
};

// 获取历史天气
const getHistoricalWeather = async (req, res) => {
  const { location: adcode } = req.params; // 期望location参数直接是adcode
  const { date } = req.query; // date参数目前未使用，但保留以防未来扩展

  try {
    if (!adcode) {
      return res.status(400).json({ message: 'Adcode is required.' });
    }

    // 尝试从Cities表获取城市名称，以便在前端显示
    let cityName = adcode; // 默认使用adcode作为城市名称，如果找不到正式名称
    const cityRecord = await City.findOne({
      where: { city_code: adcode },
      attributes: ['city_name']
    });

    if (cityRecord) {
      cityName = cityRecord.city_name;
    }

    // 获取15天前的日期
    const fifteenDaysAgo = new Date();
    fifteenDaysAgo.setDate(fifteenDaysAgo.getDate() - 15);
    fifteenDaysAgo.setHours(0, 0, 0, 0); // 设置为当天的开始

    // 从缓存中查询历史天气数据（最近15天）
    const historicalRecords = await WeatherCache.findAll({
      where: {
        city_id: adcode, // 使用adcode进行查询
        date: { [Op.gte]: fifteenDaysAgo } // 大于或等于15天前
      },
      order: [['date', 'ASC']], // 按日期升序排序
      attributes: ['date', 'temperature', 'weather_condition'] // 选择相关字段
    });

    const formattedData = historicalRecords.map(record => ({
      date: new Date(record.date).toISOString().slice(0, 10), // 确保是Date对象，然后格式化日期为 YYYY-MM-DD
      temperature: record.temperature,
      weather_condition: record.weather_condition,
    }));

    res.json({
      city_name: cityName,
      historicalWeather: formattedData
    });

  } catch (error) {
    console.error('获取历史天气失败:', error.message, error.stack);
    res.status(500).json({ error: '获取历史天气数据失败', details: error.message });
  }
};

module.exports = {
  getCurrentWeather,
  getWeatherByCityId,
  getForecastWeather,
  getHistoricalWeather,
};